package com.example.demo.controller;

import com.example.demo.service.MinIOService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("/api/minio")
public class MinIOController {

    @Autowired
    private MinIOService minIOService;

    // 上传文件
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file,
                                             @RequestParam(required = false) String bucket) {
        try {
            String fileName = minIOService.uploadFile(file, bucket);
            return ResponseEntity.ok(fileName);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("上传失败: " + e.getMessage());
        }
    }

    // 下载文件
    @GetMapping("/download/{fileName}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable String fileName,
                                               @RequestParam(required = false) String bucket) {
        try {
            InputStream stream = minIOService.getFile(fileName, bucket);
            byte[] content = stream.readAllBytes();
            stream.close();
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(content);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(("下载失败: " + e.getMessage()).getBytes());
        }
    }

    // 列出文件
    @GetMapping("/list")
    public ResponseEntity<List<String>> listFiles(@RequestParam(required = false) String bucket) {
        try {
            List<String> files = minIOService.listFiles(bucket);
            return ResponseEntity.ok(files);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(null);
        }
    }

    // 删除文件
    @DeleteMapping("/delete/{fileName}")
    public ResponseEntity<String> deleteFile(@PathVariable String fileName,
                                             @RequestParam(required = false) String bucket) {
        try {
            minIOService.deleteFile(fileName, bucket);
            return ResponseEntity.ok("删除成功");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("删除失败: " + e.getMessage());
        }
    }
}